using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input.Touch;

namespace WPCoco.Controllers
{
    public class ControllerManager : DrawableGameComponent 
    {
        #region Singleton

        static ControllerManager shared;

        public static ControllerManager Shared
        {
            get
            {
                if (shared == null)
                    shared = new ControllerManager(Coco.Shared.Game);
                return shared;
            }
        }

        #endregion

        private ControllerManager(Game game)
            : base(game)
        {
            AddController(new TouchScreen());
        }

        public TouchScreen TouchScreen
        {
            get { return GetController(0) as TouchScreen; }
        }

        Dictionary<int, Controller> Id2Ctrl = new Dictionary<int, Controller>();
        List<Controller> ctrlList = new List<Controller>();

        int id = 0;

        public int AddController(Controller ctrl) 
        {
            if (Id2Ctrl.ContainsValue(ctrl)) return -1;
            Id2Ctrl[id] = ctrl;
            ctrlList.Add(ctrl);
            ctrl.Id = id;
            ctrl.IsPluged = true;
            id++;
            return id - 1;
        }

        public bool RemoveController(Controller ctrl) 
        {
            if (!Id2Ctrl.ContainsValue(ctrl)) return false;
            if (ctrl.Id == 0) return false;
            if (Id2Ctrl[ctrl.Id] != ctrl)
                throw new InvalidOperationException("Id field never mut be modified");
            Id2Ctrl.Remove(ctrl.Id);
            ctrlList.Remove(ctrl);
            ctrl.Id = -1;
            ctrl.IsPluged = false;
            return true;
        }

        public Controller GetController(int id) 
        {
            if (!Id2Ctrl.ContainsKey(id)) return null;
            return Id2Ctrl[id];
        }

        TouchInputState touchInput = new TouchInputState();

        public override void Update(GameTime gameTime)
        {
            touchInput.Update();
            if (!touchInput.HasInformation()) return;
            foreach (var ctrl in Id2Ctrl.Values)
            {
                if (ctrl.Enabled)
                    ctrl.Update(gameTime, touchInput);
            }
        }

        public override void Draw(GameTime gameTime)
        {
            foreach (var ctrl in Id2Ctrl.Values)
            {
                if (ctrl.Enabled)
                    ctrl.Draw(gameTime);
            }
        }
    }
}
